package svgedit.gui.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import svgedit.gui.Frame;
import svgedit.gui.SVGFileFilter;

/** Shows discard changes dialog, then presents a file dialog for the
 *  user to select an existing document to edit.
 */
@SuppressWarnings("serial")
public class OpenDocumentAction extends AbstractAction {

    private Frame frame;

    /** Create this action for the given frame */
    public OpenDocumentAction(Frame frame) {
        super("Open...");
        this.frame = frame;
    }

    public void actionPerformed(ActionEvent ae) {
        String directory = frame.getPreferences().getDefaultPath();
        int option;
        File file;
        JFileChooser dialog = new JFileChooser(directory);
    	if(frame.view.getSaveState() !=0){
	        int exit =JOptionPane.showConfirmDialog(frame,"Do you want to save before exit?"
	                        ,"Confrim Exit", JOptionPane.YES_NO_CANCEL_OPTION);
	        if (exit==JOptionPane.YES_OPTION){
	        	System.out.println("----------------1");
	        	option = dialog.showSaveDialog(frame);
		        dialog.addChoosableFileFilter(new SVGFileFilter());
	            dialog.showOpenDialog(frame);
	
	            file = dialog.getSelectedFile();
	            if (file != null) {
	                frame.getPreferences().setDefaultPath(file.getPath());
	                frame.openFile(file);
	            }
	        }  
	        if (exit==JOptionPane.NO_OPTION) {
	        	System.out.println("----------------2");
	            dialog.addChoosableFileFilter(new SVGFileFilter());
	            dialog.showOpenDialog(frame);

	            file = dialog.getSelectedFile();
	            if (file != null) {
	                frame.getPreferences().setDefaultPath(file.getPath());
	                frame.openFile(file);
	            }
	        }
    	}
        
    }
}
